package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Serverr {
    private ServerSocket serversocket;
    private ExecutorService threadPool;
    public Serverr(){
        try {
            threadPool = Executors.newFixedThreadPool(30);
            System.out.println("正在启动服务器");
            serversocket = new ServerSocket(8808);
            System.out.println("服务器已启动");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while(true) {
                System.out.println("等待客户端连接...");
                Socket socket = serversocket.accept();
                System.out.println("客户端已连接");
                ClientHandler handler = new ClientHandler(socket);
                threadPool.execute(handler);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private class ClientHandler implements Runnable{
        private Socket socket;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        public void run(){
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(isr);
                String str;
                while((str = br.readLine())!=null)
                System.out.println("客户端说:" + str);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[]args){
        Serverr serverr = new Serverr();
        serverr.start();
    }

}
